{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7f161eb8-7973-4c4e-ac9a-c85979a9b7a8",
   "metadata": {},
   "source": [
    "<h2> Chatbot for Dental Office</h2>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "c9883c8a-1ea8-406c-81e0-18fbf6c5d8b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from openai import OpenAI\n",
    "import gradio as gr\n",
    "import requests\n",
    "from bs4 import BeautifulSoup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "72fe1eb9-a8b1-48f1-9c4f-eefb9714d8fb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OpenAI API Key exists and begins sk\n",
      "Anthropic API Key exists and begins sk\n",
      "Google API Key exists and begins AI\n"
     ]
    }
   ],
   "source": [
    "# Load environment variables in a file called .env\n",
    "# Print the key prefixes to help with any debugging\n",
    "\n",
    "load_dotenv(override=True)\n",
    "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
    "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
    "google_api_key = os.getenv('GOOGLE_API_KEY')\n",
    "\n",
    "if openai_api_key:\n",
    "    print(f\"OpenAI API Key exists and begins {openai_api_key[:2]}\")\n",
    "else:\n",
    "    print(\"OpenAI API Key not set\")\n",
    "    \n",
    "if anthropic_api_key:\n",
    "    print(f\"Anthropic API Key exists and begins {anthropic_api_key[:2]}\")\n",
    "else:\n",
    "    print(\"Anthropic API Key not set\")\n",
    "\n",
    "if google_api_key:\n",
    "    print(f\"Google API Key exists and begins {google_api_key[:2]}\")\n",
    "else:\n",
    "    print(\"Google API Key not set\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3bf7a992-ded3-42b3-b207-1a5077804466",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize\n",
    "\n",
    "openai = OpenAI()\n",
    "MODEL = 'gpt-4o-mini'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "4ecd96d8-2e87-4a39-9784-178aa4424667",
   "metadata": {},
   "outputs": [],
   "source": [
    "#scrape website\n",
    "\n",
    "def get_website_text(url):\n",
    "    try:\n",
    "        response = requests.get(url)\n",
    "        response.raise_for_status()\n",
    "        \n",
    "        soup = BeautifulSoup(response.text, \"html.parser\")\n",
    "        \n",
    "        # Remove script and style elements\n",
    "        for tag in soup([\"script\", \"style\", \"noscript\"]):\n",
    "            tag.decompose()\n",
    "\n",
    "        # Extract visible text\n",
    "        text = soup.get_text(separator=\"\\n\")\n",
    "        \n",
    "        # Clean up whitespace\n",
    "        lines = [line.strip() for line in text.splitlines()]\n",
    "        content = \"\\n\".join(line for line in lines if line)\n",
    "\n",
    "        return content[:100000]  \n",
    "    except Exception as e:\n",
    "        return f\"Error fetching website content: {e}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "c0fc0537-e0b8-450d-8457-b00669c5df86",
   "metadata": {},
   "outputs": [],
   "source": [
    "url = \"https://rooseveltislandadvanceddentistry.com/\"\n",
    "website_content = get_website_text(url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "25e118d7-5adb-4978-bdac-83c12e119de2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"Roosevelt Island Advanced Dentistry | Pediatric Dentist\\nBusiness Hours:\\nMonday to Saturday 9 AM to 5 PM\\n(212) 752-8722\\n501A Main St, New York, NY 10044, United States\\nRoosevelt Island\\ncontact us\\nBook an appointment\\nOur Team\\nPediatric Procedures\\nPediatric Services\\nPediatric Topics\\nProsthodontics Procedures\\nDental Implants\\nGeneral Dentistry\\nServices\\nCosmetic Dentistry\\nOral Hygiene\\nEmergency\\nOrthodontics\\nOnline Forms\\nTestimonials\\nOur Team\\nPediatric Procedures\\nPediatric Services\\nPediatric Topics\\nProsthodontics Procedures\\nDental Implants\\nGeneral Dentistry\\nServices\\nCosmetic Dentistry\\nOral Hygiene\\nEmergency\\nOrthodontics\\nOnline Forms\\nTestimonials\\nBusiness Hours:\\nMonday to Saturday 9 AM to 5 PM\\n(212) 752-8722\\n501A Main St, New York, NY 10044, United States\\nRoosevelt Island\\ncontact us\\nBook an appointment\\nNEW YORK PEDIATRIC DENTIST\\nThe best and only Pediatric Dentist Specialist in Roosevelt Island, NY.\\nThe best and only Pediatric Dentist Specialist in Roosevelt Island, NY.\\nRoosevelt Island Advanced Dentistry offers comprehensive general dentistry services in Roosevelt Island, NY.\\nRoosevelt Island Advanced Dentistry provides expert prosthodontics in Roosevelt Island, NY.\\nThe best and only Pediatric Dentist Specialist in Roosevelt Island, NY.\\nRoosevelt Island Advanced Dentistry offers comprehensive general dentistry services in Roosevelt Island, NY.\\nRoosevelt Island Advanced Dentistry provides expert prosthodontics in Roosevelt Island, NY.\\nbook an appointment\\nCall :\\n(212) 752-8722\\nleave a review\\nRoosevelt Island Dentistry nyc\\nServices We Provide\\nPediatric Specialty Procedures\\nLearn more\\nOrthodontics\\nLearn more\\nProsthodontics Specialty Procedures\\nLearn more\\nCosmetic Dentistry\\nLearn more\\nDental Implants\\nLearn more\\nGeneral Dentistry\\nLearn more\\nDENTAL ICON(outline)\\nOral Hygiene\\nLearn more\\nSmile Makeover\\nLearn more\\nbook an appointment\\ncontact us\\nOur Team\\nabout us\\ntestimonials\\nDr. skomial\\nProsthodontist-Implant Specialist\\nDr. Skomial is an active member of American Dental Association and American College of Prosthodontists. He is originally from Poland and speaks\\nLearn more\\nDr. Chen\\nBoard Certified Pediatric Dentist\\nDonna Chen, DDS is a compassionate dentist who loves building relationships with her patients. She caters to children’s individualized needs and\\nLearn more\\nDr. Correa\\nBoard Certified Pediatric Dentist\\nDr. Lizeth Correa is a pediatric dentist known for her warm and friendly approach to treating young patients. Dr. Correa places emphasis\\nLearn more\\nDr. Regina Mathai, DDS MPH\\nBoard Eligible Pediatric Dentist\\nDr. Regina, from Hudson Valley, NY, earned a Biology and Spanish degree from Binghamton and a Master's in Public Health from Hofstra.\\nLearn more\\nDr. Buchbinder\\nOrthodontist\\nDr. William Buchbinder (Dr. Billy) is an orthodontic specialist serving patients across the Greater New York area. Combining clinical excellence with a warm, approachable style.\\nLearn more\\nDr. Matthew Lee, DMD\\nGeneral Dentist\\nDr. Matthew Lee, a NYC native, holds a Biology degree and a Master's in Biomedical Sciences from Rutgers, where he also attended dental school.\\nLearn more\\nDr. Jason Tu, DDS\\nGeneral Dentist\\nDr. Jason Tu was born and raised in Vancouver, Canada. He completed his undergraduate studies at UBC and dental school at NYU.\\nLearn more\\nDr. Jeanne Helbig, DMD\\nGeneral Dentist\\nDr. Jeanne Helbig is a general dentist who believes in providing\\ncompassionate and comprehensive care to each of her patients.\\nLearn more\\nWhy we stand out?\\nRoosevelt Island Advanced Dentistry always places patients at the center of our attention, and concentrate on improving their experience with the aid of technologies.\\nGet your services right\\nGet rid of your pain, stress, and enduring with our dental services. It’s a priority to relieve the pain and damage to your mouth in surgeon as much as possible.\\nwhy choose us\\nReasons why we're widely favored\\ncontact us\\nfaqs\\nHome Heart\\nWork With Hearts\\nWe care for your dental health with a great compassion & understanding so that you can have the best smile.\\nPrecise Diagnosis\\nWhen your teeth are decayed or damaged, we use modern tools to detect the area and provide treatment.\\nServe with Smile\\nThe smile never fades on our doctors’ faces as they always want to create an atmosphere that feels comfortable.\\nAnnual Check-ups\\nWe provide annual check-up for dental health conditions and offer many promotions for members of our center.\\nHelp at Hand\\nWe are ready to check for any teeth issue at our center and at any time of the day, even on weekends & holidays.\\nFlexible Installment\\nWe allow periodic installments of purchasing costs in case customers are unable to afford the price of services.\\nFAQs\\nYou may find an answer to your question here.\\nWhy choose a Pediatric Dentist?\\nPediatric Dentistry is the dental specialty recognized by the American Dental Association (ADA), which provides comprehensive dental care for all children, from infancy to adolescence. Pediatric dentists promote the dental health of children as well as serve as educational resources for parents.\\nA Pediatric Dentist is a practitioner who has completed an additional two years of post-doctorate training after dental school. The specialty-focused training includes child psychology, behavioral guidance, preventative techniques, and restorative dentistry. A pediatric dentist also received training in treating handicapped or chronically ill children as well.\\nWhat can I expect during my visit?\\nThe pediatric dentist will review your child’s medical and dental history. They will gently examine your child’s teeth, oral tissues, and jaws. The teeth will be cleaned and polished, followed by the application of a fluoride solution, if necessary.\\nYour pediatric dentist won’t talk just to you about dental health, she will talk to your child with easily understandable words, pictures, and ideas. Your child will be motivated to take responsibility for a healthy smile.\\nDo you treat children with special needs?\\nNo, but we have a 'Refuse a Service' option, and here is how it works. If, during some of the beginning stages of preparation, you see that the service does not satisfy your expectations, you can terminate the contract and not pay the final amount of money. Since we sign a service contract for all the events, the conditions, such as the amounts of money and payment dates, are specified in the signed documents. Therefore, we advise you to read the contract carefully and pay specific attention to the paragraph that describes the mentioned data.\\nWhen should my child's first dentist visit be?\\nThe American Academy of Pediatric Dentistry recommends a child’s first dental visit by their first birthday, or sooner. A dental check-up twice a year is recommended for most children. Some children need more frequent dental visits because of increased risk of tooth decay, unusual growth patterns or poor oral hygiene. Your pediatric dentist will let you know the best appointment schedule for your child.\\nRegular dental visits help your child stay cavity-free. Teeth cleanings remove debris that build up on the teeth, irritate the gums and cause decay. Fluoride treatments renew the fluoride content in the enamel, strengthening teeth and preventing cavities. Hygiene instructions improve your child’s brushing and flossing, leading to cleaner teeth and healthier gums.\\nTooth decay isn’t the only reason for a dental visit. Your pediatric dentist provides an ongoing assessment of changes in your child’s oral health. For example, your child may need additional fluoride, dietary changes, or sealants for ideal dental health. The pediatric dentist may identify orthodontic problems and suggest treatment to guide the teeth as they emerge in the mouth. Speak to your pediatric dentist today.\\nContact Us Today!\\nGet in Touch for Personalized Pediatric Dentistry in Roosevelt Island!\\nAddress\\n501A Main St, New York, NY 10044,\\nUnited States\\nRoosevelt Island\\nphone\\n(212) 752-8722\\nemail\\nmoc.liamg%40cllevollatned\\nbusiness hours\\nMonday to Saturday 9 AM to 5 PM\\nRoosevelt Island Advanced Dentistry\\nRoosevelt Island Advanced Dentistry\\nPhone:\\n(212) 759-3666\\nBusiness Hours:\\nMonday to Saturday 9 AM to 5 PM\\nQuick Links\\nPediatric Specialty Procedures\\nProsthodontics Specialty Procedures\\nGeneral Dentistry\\nLegal Pages\\nPrivacy Policy\\nAccessibility Statement\\n© Created by\\nDearDoc\\nAll Rights Reserved Roosevelt Island Advanced Dentistry.\\nRoosevelt Island Advanced Dentistry\\nRoosevelt Island Advanced Dentistry\\nPhone:\\n(212) 759-3666\\nBusiness Hours:\\nMonday to Saturday 9 AM to 5 PM\\nQuick Links\\nPediatric Specialty Procedures\\nProsthodontics Specialty Procedures\\nGeneral Dentistry\\nLegal Pages\\nPrivacy Policy\\nAccessibility Statement\\n© Created by\\nDearDoc\\nAll Rights Reserved Roosevelt Island Advanced Dentistry.\""
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "website_content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "7c560358-3932-4599-b608-fdfb8d99a784",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_message = (\n",
    "    \"You are a helpful assistant for a dental office. Your job is to welcome the patient. Use the information below to answer patient questions \"\n",
    "    \"about services, office hours, insurance, contact details, doctors and booking appointments.\\n\\n\"\n",
    "    f\"Website content:\\n{website_content}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "b976152b-77c0-4901-bec6-50ac32c8cfbb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "    messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
    "    \n",
    "    print(\"History is:\")\n",
    "    print(history)\n",
    "    print(\"And messages is:\")\n",
    "    print(messages)\n",
    "\n",
    "    stream = openai.chat.completions.create(model=MODEL, messages=messages, stream=True)\n",
    "\n",
    "    response = \"\"\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or ''\n",
    "        yield response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "48e3852e-557c-4a7a-9ada-41cd6bbd6167",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7872\n",
      "* To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7872/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat, type=\"messages\").launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f224861-c8a1-40e6-b07a-4d7d4b5d9484",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
